package com.sright.bcard.enterprise.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.sright.bcard.common.service.share.mvcresolver.EnableLoginAuth;
import com.sright.bcard.enterprise.web.context.RequestStorager;
import com.sright.bcard.user.share.service.AuthService;
import com.sright.common.response.SrightResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    public final static String USER_ID_KEY = "userId";
    public final static String USER_TOKEN_KEY = "token";

    @Autowired
    private AuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        if (needLogin(handler, request)) {
            String json = JSONObject.toJSONString(SrightResponse.defaultUnloginError());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(json);
            out.close();
            response.flushBuffer();
            return false;
        }
        return true;
    }

    private boolean needLogin(Object handler, HttpServletRequest request) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法上的注解
            EnableLoginAuth loginRequired = handlerMethod.getMethod().getAnnotation(EnableLoginAuth.class);
            // 如果方法上的注解为空 则获取类的注解
            if (loginRequired == null) {
                loginRequired = handlerMethod.getMethod().getDeclaringClass().getAnnotation(EnableLoginAuth.class);
            }
            // 如果标记了注解，则判断权限
            if (loginRequired != null) {
                // 查看是否已经登录
                String token = request.getHeader("Authorization");
                if (token == null || token.isEmpty()) {
                    return true;
                }
                Long userId = authService.queryUserIdByToken(token);
                RequestStorager.setUserId(userId);
                RequestStorager.setToken(token);

                return false;
            }
        }
        return false;
    }
}
